package com.jincp.common.base;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import java.util.Stack;

/**
 * =========================================================
 * 类名： APPActivityManager
 * 类描述：activity堆栈式管理
 * 创建日期 16/10/12
 * =========================================================
 */
public class APPActivityManager implements Application.ActivityLifecycleCallbacks {

    private static final APPActivityManager instance = new APPActivityManager();
    private Stack<Activity> activities = new Stack<>();


    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        this.activities.push(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        this.activities.remove(activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        this.activities.remove(activity);
        this.activities.push(activity);
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    public Activity getTopActivity() {
        return this.activities.isEmpty() ? null : this.activities.peek();
    }

    public void finish(Activity targetActivity) {
        try {
            for (Activity activity : activities) {
                if (activity == targetActivity) {
                    activities.remove(activity);
                    activity.finish();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void finish(Class targetActivity) {
        try {
            for (Activity activity : activities) {
                if (activity.getClass().getSimpleName().equals(targetActivity.getSimpleName())) {
                    activities.remove(activity);
                    activity.finish();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void finishAll() {
        try {
            for (Activity activity : activities) {
                activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        activities.clear();
    }

    private APPActivityManager() {
    }

    public static APPActivityManager getInstance() {
        return instance;
    }


}
